import axios from "axios"
import { ElLoading as Loading } from "element-plus"
import store from "@/store/index"

let loadingInstance = null //蒙版实例
let timer = null //定时器
// 创建axios实例
const instance = axios.create({ timeout: 1000 * 60 })
/**
 * 设置默认请求头
 */
instance.defaults.headers.post["Content-Type"] =
  "application/x-www-form-urlencoded;charset=UTF-8"
instance.defaults.headers.delete["Content-Type"] =
  "application/x-www-form-urlencoded;charset=UTF-8"
instance.defaults.headers.put["Content-Type"] =
  "application/x-www-form-urlencoded;charset=UTF-8"
//添加默认请求路径
if (process.env.NODE_ENV == "development") {
  instance.defaults.baseURL = "/dev_api"
} else if (process.env.NODE_ENV == "production") {
  instance.defaults.baseURL = "/api"
}
/**
 * 请求拦截器
 * 1. 每次请求前，添加蒙板
 */
instance.interceptors.request.use(
  (config) => {
    const token = store.getters["user/token"]
    const userRole = store.getters['user/userRole']
    if (token) {
      config.headers.Authorization = token
    }
    if (userRole) {
      config.headers.userRole = userRole
    }
    // 添加遮罩层
    if (timer !== null) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      //如果存在则关闭
      if (loadingInstance !== null) {
        loadingInstance.close()
      }
      loadingInstance = Loading.service({
        lock: true,
        text: "努力加载中！",
        background: "rgba(0, 0, 0, 0.65)"
      })
    }, 800)
    return config
  },
  (error) => Promise.error(error)
)
/**
 * 响应拦截器
 *
 */
instance.interceptors.response.use(
  // 请求成功
  (res) => {
    //如果请求返回快的话，就不需要loading
    // 清除定时器
    clearTimeout(timer)
    timer = null
    // 请求返回后，关闭loading
    if (loadingInstance !== null) {
      loadingInstance.close()
    }
    if (res.status === 200) {
      const { code } = res.data
      if (code === 5001 || code === 5002) {
        store.commit('user/clear_userInfo')
      }
      return Promise.resolve(res.data)
    } else {
      return Promise.reject(res.data)
    }
  },
  (error) => {
    //如果请求返回快的话，就不需要loading
    // 清除定时器
    clearTimeout(timer)
    timer = null
    // 请求返回后，关闭loading
    if (loadingInstance !== null) {
      loadingInstance.close()
    }
    return Promise.reject(error)
  }
)
export default instance
